﻿using Api.Common;
using Api.Web.helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Api.Web.filter
{
    public class IsLoginAttribute : AuthorizeAttribute
    {
        private readonly bool _authorize;

        /// <summary>
        /// 參數使用false的時候表示不檢查
        /// </summary>
        /// <param name="authorize"></param>
        public IsLoginAttribute(bool authorize = true)
        {
            _authorize = authorize;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!_authorize)
            {
                return true;
            }
            return Th.IsLogin;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;

            object siteId;
            filterContext.RouteData.Values.TryGetValue("siteId", out siteId);
            //string returnUrl = (context.Request.Url != null) ? context.Request.Url.ToString() : string.Empty;
            string returnUrl = string.Empty;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["isajax"])) //表示为ajax请求
            {
                AjaxMsgHelper.Response(true, "請重新登錄", null, "", false);//请重新登录
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary()
                {
                    { "area",""},
                    {"controller","Account"},
                    {"action","Login" },
                    {"returnUrl", returnUrl}
                });
            }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            HandleUnauthorizedRequest(filterContext);
        }
    }
}